﻿using System;
using UnityEngine;
using System.Collections.Generic;
using Common;


public class TrailEffect : IBase
{
    public float height = 2.7f;
    public float time = 0.5f;
    public float minDistance = 0.01f;
    public Color startColor = Color.white;
    public Color endColor = new Color(1, 1, 1, 0);
    public AnimationState Animation;
    private List<TrailItem> sections = new List<TrailItem>();
    private Transform trail;
    private Vector3 position = Vector3.zero;
    private float now = 0;
    private Material material;
    private MeshFilter meshFilter;
    private Mesh mesh;
    private MeshRenderer meshRenderer;
    private Vector3[] vertices;
    private Vector2[] uv;
    private Color[] colors;
    private int[] triangles;
    private Matrix4x4 localSpaceTransform;
    private Color interpolatedColor;
    private float u;
    private TrailItem currentSection;
    private float endTime;
    private float startTime;
    private bool ready = false;
    private bool waitEnd = false;
    public TrailEffect(Transform transform, AnimationState animation, float start, float end)
    {
        Animation = animation;
        trail = new GameObject().transform;
        trail.name = trail.GetInstanceID().ToString();
        trail.parent = transform.parent;
        trail.localPosition = transform.localPosition;
        trail.localRotation = transform.localRotation;

        meshRenderer = trail.gameObject.AddComponent<MeshRenderer>();
        meshRenderer.material = Resources.Load("Effect/trail") as Material;
        meshRenderer.castShadows = false;
        meshRenderer.receiveShadows = false;

        material = trail.renderer.material;
        meshFilter = trail.gameObject.AddComponent<MeshFilter>();
        mesh = meshFilter.mesh;
        startTime = start;
        endTime = end;
    }
    private bool end = false;
    public bool End
    {
        get { return end; }
        set { end = value; }
    }
    public void Update()
    {

    }
    public void FixedUpdate()
    {
        //Debug.Log("sdsdsd");
    }
    public void LateUpdate()
    {
        //Debug.Log("ready:" + ready + ",waitEnd:" + waitEnd);
        if (waitEnd && End) return;
        if (ready)
        {
            if (!waitEnd && Animation.time >= endTime)
            {
                waitEnd = true;
                return;
            }
        }
        else
        {
            if (Animation.time >= startTime)
            {
                ready = true;
            }
            else return;
        }
        position = trail.position;
        now = Time.time;
        while (sections.Count > 0 && now > sections[0].Time + time)
        {
            sections.RemoveAt(0);
        }
        if (!waitEnd && (sections.Count == 0 || (sections[0].Point - position).sqrMagnitude > minDistance * minDistance))
        //if (sections.Count == 0 || Vector3.Distance(sections[0].Point, position) > minDistance)
        {
            var section = new TrailItem();
            section.Point = position;
            section.UpDir = position + trail.TransformDirection(Vector3.up) * height;
            section.Time = now;
            sections.Add(section);
        }
        if (waitEnd && sections.Count == 0)
        {
            Delete();
            End = true;
        }
        if (sections.Count < 2) return;

        vertices = new Vector3[sections.Count * 2];
        colors = new Color[vertices.Length];
        uv = new Vector2[vertices.Length];

        localSpaceTransform = trail.worldToLocalMatrix;
        for (var i = 0; i < sections.Count; i++)
        {
            currentSection = sections[i];
            u = (now - currentSection.Time) / time;
            vertices[i * 2 + 0] = localSpaceTransform.MultiplyPoint(currentSection.Point);
            vertices[i * 2 + 1] = localSpaceTransform.MultiplyPoint(currentSection.UpDir);
            uv[i * 2 + 0] = new Vector2(u, 0);
            uv[i * 2 + 1] = new Vector2(u, 1);
            interpolatedColor = Color.Lerp(startColor, endColor, u);
            colors[i * 2 + 0] = interpolatedColor;
            colors[i * 2 + 1] = interpolatedColor;
        }
        triangles = new int[(sections.Count - 1) * 2 * 3];
        for (int i = 0; i < triangles.Length / 6; i++)
        {
            triangles[i * 6 + 0] = i * 2;
            triangles[i * 6 + 1] = i * 2 + 1;
            triangles[i * 6 + 2] = i * 2 + 2;

            triangles[i * 6 + 3] = i * 2 + 2;
            triangles[i * 6 + 4] = i * 2 + 1;
            triangles[i * 6 + 5] = i * 2 + 3;
        }

        mesh.Clear();
        mesh.vertices = vertices;
        mesh.colors = colors;
        mesh.uv = uv;
        mesh.triangles = triangles;
    }
    public void Delete()
    {
        GameObject.Destroy(material);
        GameObject.Destroy(trail.renderer);
        GameObject.Destroy(mesh);
        GameObject.Destroy(meshFilter);
    }
    public void Start()
    {
        
    }
}
public class TrailItem
{
    public Vector3 Point;
    public Vector3 UpDir;
    public float Time;
}
 
